<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    :title="form.id ? '编辑' : '新增'"
    width="1200"
    show-footer
    show-zoom
    resize
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <template #default>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-align="right"
        label-width="120"
        label-position="top"
      >
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="上级类目">
              <el-cascader
                v-model="form.p_id"
                :options="treeData"
                :props="defaultProps"
                placeholder="请选择"
                clearable
                class="w-full"
                :disabled="form.id > 0"
                @change="change_p"
              />
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="类目名称" prop="name">
              <el-input v-model.trim="form.name" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="4" class="mt-7">
            <el-switch
              v-model="form.status"
              :active-value="1"
              :inactive-value="2"
              active-text="启用"
              inactive-text="禁用"
              inline-prompt
            />
          </el-col>
          <el-col :span="10">
            <el-form-item label="类目英文名称" prop="en_name">
              <el-input v-model.trim="form.en_name" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="类目简称(仅支持输入英文、数字)" prop="code">
              <el-input
                v-model.trim="form.code"
                placeholder="请输入"
                clearable
                oninput="value=value.replace(/[\u4e00-\u9fa5]/g, '')"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="py-2 text-base">关联数据</div>
        <el-row :gutter="21">
          <el-col :span="8">
            <el-form-item label="分类类型">
              <el-select
                class="w-full"
                v-model="form.category_type"
                placeholder="分类类型"
                clearable
              >
                <el-option
                  v-for="item in classifyTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购员类型">
              <el-select
                class="w-full"
                v-model="form.purchaser_type"
                placeholder="采购员类型"
                clearable
              >
                <el-option
                  v-for="item in purchasePersonOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属部门">
              <el-select
                class="w-full"
                v-model="form.depart_id"
                placeholder="所属部门"
                clearable
              >
                <el-option
                  v-for="item in primaryDepartment"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="handleType == 'edit'">
          <div class="flex justify-between">
            <div class="py-2 text-base">关联平台分类</div>
            <el-button type="primary" @click="handleAssociatedPlatform(form)"
              >关联平台分类</el-button
            >
          </div>
          <el-table
            :data="form.base_category_platform"
            height="400"
            style="width: 100%"
            highlight-current-row
            :header-cell-style="{
              color: '#333333',
              background: '#F6FAFF',
            }"
            border
          >
            <el-table-column prop="platform_code" label="平台" width="80">
            </el-table-column>
            <el-table-column prop="site_code" label="站点" width="80"> </el-table-column>
            <el-table-column label="平台分类详情">
              <template #default="{ row }">
                <el-table
                  :data="row.base_category_platform_detail"
                  border
                  :header-cell-style="{
                    color: '#333333',
                    background: '#F6FAFF',
                  }"
                >
                  <el-table-column prop="platform_category_id_text" label="平台分类">
                  </el-table-column>
                  <el-table-column prop="keyword" label="备注"> </el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="关联时间" width="180">
            </el-table-column>
            <el-table-column prop="created_user_text" label="操作人" width="160">
            </el-table-column>
            <el-table-column prop="tag_name" label="操作" width="80">
              <template #default="{ row, $index }">
                <el-button type="danger" link>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save(formRef)"
        >保 存</el-button
      >
    </template>
  </el-dialog>
  <AssociatedPlatform ref="AssociatedPlatformRef"></AssociatedPlatform>
</template>
<script setup name="ComModal">
import {
  getBaseBackColumnsdetails,
  saveBackendClassification,
  updateBackendClassification,
} from "../api";
import { reactive, ref, toRefs, getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
import { purchasePersonOptions, classifyTypeOptions } from "../data.js";
import useCommonStore from "@/store/modules/common";
const commonStore = useCommonStore();

import AssociatedPlatform from "./AssociatedPlatform.vue";

const visible = ref(false);
const loading = ref(false);
const formRef = ref(null);
const emits = defineEmits(["query"]);
const { proxy } = getCurrentInstance();
const props = defineProps({
  treeData: {
    type: Array,
    default: () => {
      return [];
    },
  },
});

const { treeData } = toRefs(props);

const defaultProps = {
  children: "son",
  label: "name",
  value: "id",
  checkStrictly: true,
};
const data = reactive({
  form: {},
  rules: {
    p_id: [{ required: true, message: "请选择上级类目", trigger: "change" }],
    name: [{ required: true, message: "请输入类目名称" }],
    en_name: [{ required: true, message: "请输入类目英文名称" }],
    code: [{ required: true, message: "请输入类目简称" }],
    operator_department: [{ required: true, message: "请选择运营部门" }],
  },
  handleType: null,
  primaryDepartment: [],
  load: false,
});
const { rules, form, handleType, primaryDepartment, load } = toRefs(data);
const open = async (data) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  visible.value = true;
  getPrimaryDepartment();
  handleType.value = data.id ? "edit" : "add";
  if (data.id) {
    getDetails(data);
  }
  form.value.status = 1;
};

const getDetails = async (data) => {
  try {
    const res = await getBaseBackColumnsdetails({
      id: data.id,
    });
    form.value = res.data;
  } catch (e) {
    throw Error(e);
  }
};

const change_p = (val) => {
  console.log(val);
  if (!val.length) return;
  if (val.length == 4) {
    ElMessage.error("产品分类最多支持4级");
    nextTick(() => {
      form.value.p_id = "";
    });
    return;
  }
  form.value.p_id = val[val.length - 1];
};

const save = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      const formData = Object.assign({}, form.value);
      formData.p_id = formData.p_id || 0;
      if (formData.id) {
        updateBackendClassification(formData)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally((e) => {
            loading.value = false;
          });
      } else {
        saveBackendClassification(formData)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally((e) => {
            loading.value = false;
          });
      }
    }
  });
};

const initForm = () => {
  form.value = getForm();
};
// 初始化
const getForm = () => {
  return {
    p_id: 0,
    status: 1,
    name: "",
    en_name: "",
    code: "",
    operator_department: [],
    develop_department: [],
    design_department: [],
  };
};

onMounted(() => {
  if (!commonStore.departmentOptions) {
    commonStore.getDepartmentList();
  }
});

const close = () => {
  initForm();
  visible.value = false;
};
defineExpose({ open });

const AssociatedPlatformRef = ref();
// 关联平台分类
const handleAssociatedPlatform = (data) => {
  AssociatedPlatformRef.value.open(data);
};

const getPrimaryDepartment = () => {
  const departmentOptions = commonStore.departmentOptions;
  if (!departmentOptions || departmentOptions.length === 0) {
    return;
  }
  const find = commonStore.departmentOptions.find((i) => i.id == 2);
  // 处理找不到匹配项的情况
  if (find) {
    primaryDepartment.value = find.sub;
  } else {
    // 根据业务需求处理找不到匹配项的情况
    console.warn(`未找到名为 "${DEPARTMENT_NAME}" 的部门`);
  }
};
</script>
